from config import logger
import json
from mysql_server import MYSQLMCPServer

mysql_server = MYSQLMCPServer()


async def connect_database(
    host: str = "localhost",
    port: int = 3306,
    user: str = "root",
    password: str = "123456",
    database: str = "school",
) -> str:
    try:
        config = {
            "host": host,
            "port": port,
            "user": user,
            "password": password,
            "database": database,
        }
        result = await mysql_server.connect_database(config)
        return json.dumps(result, ensure_ascii=False, indent=2)
    except Exception as e:
        logger.error(f"连接失败:{str(e)}")
        error_result = {"success": False, "message": f"连接失败:{str(e)}"}
        return json.dumps(error_result, ensure_ascii=False, indent=2)


async def get_database_info() -> str:
    try:
        info = mysql_server.db_manager.get_database_info()
        return json.dumps(info, ensure_ascii=False, indent=2)
    except Exception as e:
        logger.error(f"获取数据库信息失败:{str(e)}")
        error_result = {"success": False, "message": f"获取数据库信息失败:{str(e)}"}
        return json.dumps(error_result, ensure_ascii=False, indent=2)


async def execute_sql(sql: str) -> str:
    try:
        result = await mysql_server.execute_sql(sql)
        return json.dumps(result, ensure_ascii=False, indent=2)
    except Exception as e:
        logger.error(f"执行SQL语句失败:{str(e)}")
        error_result = {"success": False, "message": f"执行SQL语句失败:{str(e)}"}
        return json.dumps(error_result, ensure_ascii=False, indent=2)


async def natural_language_query(query: str) -> str:
    try:
        result = await mysql_server.natural_language_query(query)
        return json.dumps(result, ensure_ascii=False, indent=2)
    except Exception as e:
        logger.error(f"查询失败:{str(e)}")
        error_result = {"success": False, "message": f"查询失败:{str(e)}"}
        return json.dumps(error_result, ensure_ascii=False, indent=2)
